package org.jsets.fastboot.util;

import lombok.SneakyThrows;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;

/**
 * TODO
 *
 * @author wangjie (https://github.com/wj596)
 * @date 2022.01.11 13:56
 */
public class FileUtils {

    public static String pathJoin(String ...paths){
        StringBuilder sb = new StringBuilder();
        for (String p: paths){
            if(sb.length()>0){
                sb.append(File.separator);
            }
            sb.append(p);
        }
        return sb.toString();
    }

    /**
     * 创建目录 如果不存在
     */
    public static void mkdirIfNecessary(String path) {
        File f = new File(path);
        if(f.exists()) {
            return;
        }
        if(f.isFile()) {
            return;
        }
        f.mkdirs();
        f = null;
    }

    /**
     * 创建文件 如果不存在
     */
    @SneakyThrows
    public static void createIfNecessary(String path) {
        File f = new File(path);
        if(f.exists()) {
            return;
        }
        mkdirIfNecessary(f.getParent());
        f.createNewFile();
        f = null;
    }
    
    /**
     * 创建文件 如果不存在
     */
    public static void removeIfNecessary(String path) {
        File f = new File(path);
        if(f.exists()) {
            return;
        }
        f.delete();
        f = null;
    }
    
    
	/**
	 * 获取文件名称(不含后缀)
	 * @param fileFullName 文件全名称
	 * @return 
	 */
	public static String getFileName(String fileFullName) {
		int dotIndex = fileFullName.lastIndexOf('.');
		return (dotIndex == -1) ? fileFullName : fileFullName.substring(0, dotIndex);
	}
    
	/**
	 * 获取文件后缀
	 * @param fileFullName 文件全名称
	 * @return 
	 */
	public static String getExtension(String fileFullName) {
		int dotIndex = fileFullName.lastIndexOf('.');
		return (dotIndex == -1) ? "" : fileFullName.substring(dotIndex + 1);
	}
	
	public static String readAsString(String filePath) {
		if (StringUtils.isEmpty(filePath)) {
			throw new RuntimeException("文件路径为空");
		}

		File file = new File(filePath);
		if (!file.exists()) {
			throw new RuntimeException("文件不存在");
		}

		try (BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file))) {
			byte[] buff = new byte[1024];
			StringBuilder builder = new StringBuilder();
			int read;
			while ((read = stream.read(buff)) != -1) {
				builder.append(new String(buff, 0, read, StandardCharsets.UTF_8));
			}
			String context = builder.toString();
			return context;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}